package com.baseframe.launch.utils;

import lombok.SneakyThrows;
import org.reflections.Reflections;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class ClazzScanUtil {


    /**
     * 扫描包
     * @param source
     * @param path
     * @return
     * @param <T>
     */
    @SneakyThrows
    public static <T> List<T> scan(Class<T> source, String path){
        Reflections reflections = new Reflections(path);
        Set<Class<? extends T>> classSet = reflections.getSubTypesOf(source);

        List<T> entityList = new ArrayList<>();

        for (Class<? extends T> clazz : classSet) {
            T entity = null;
            try {
                Constructor<? extends T> constructor = clazz.getConstructor();
                entity = constructor.newInstance();
            } catch (NoSuchMethodException e) {
                throw new RuntimeException("此方法扫描到的类，必须包含一个空参构造用于实例化对象",e);
            }
            entityList.add(entity);
        }

        return entityList;

    }


}
